<template>
	<view class="schedule_style">
		<g-watermark/>
		<LuncCalendar :showLunar="false" @dayChange="handleDayChange" @swiperChange="handleMonthChange"
			:showShrink="true" @shrinkClick="handleShrinkClick" ref="luncCalendarRef">
			<template v-slot:headerRight>
				<view style="padding-right: 50upx;">
					<u-icon name="list-dot" style="margin-right: 20upx;" @click="sheetShow=true"></u-icon>
					<u-icon name="plus" @click="handlePlus" v-if="currentMode==0"></u-icon>
					<u-icon name="plus" @click="handleAddUser" v-if="currentMode==2"></u-icon>
					<u-action-sheet :list="sheetList" v-model="sheetShow" @click="handleSheetClick"></u-action-sheet>
					<SelectUser ref="selectUserRef" @confirm="handleSelectUserConfirm" />
				</view>
			</template>
		</LuncCalendar>
		<view class="schedule_list">
			<view style="background-color: #fff;">
				<template v-if="currentMode==0">
					<UserGroup :type="currentMode" @success="handleUserSuccess" @handleActionType="handleActionType"
						:key="currentMode" />
				</template>
				<template v-else-if="currentMode==1">
					<UserGroup :list="deptUsers" :type="currentMode" @success="handleUserSuccess" :key="currentMode" />
				</template>
				<template v-else-if="currentMode==2">
					<UserGroup :list="plainOptions" @success="handleUserSuccess" @delete="handleDelFavorite"
						:type="currentMode" :key="currentMode" />
				</template>
				<template v-else-if="currentMode==3">
					<UserGroup :list="leaders" :type="currentMode" @success="handleUserSuccess" :key="currentMode" />
				</template>
			</view>
			<view style="padding: 20upx;">
				<uni-swipe-action>
					<uni-swipe-action-item v-for="(item, index) in list" :key="index">
						<view class="list_box" @click="handleItem(item)">
							<template v-if="currentMode==0">
								<view class="list_box_left">
									<view class="">
										{{item.start}}
									</view>
								</view>
								<view class="list_box_right">
									<view style="line-height: 1.5;">
										{{item.title}}
									</view>
									<view
										style="color:#3485e9;margin-top: 10upx; display: flex;justify-content: space-between;align-items: center;">
										{{'今天'}} {{item.start}} - {{item.end}}
										<view>
											<u-tag :text="getActionType(item.actionType)" mode="light"></u-tag>
										</view>
									</view>
								</view>
							</template>
							<template v-else>
								<view class="list_box_left" style="width: 30%;">
									<view class="">
										{{item.day}}
									</view>
									<view class="">
										{{item.realName}}
									</view>
								</view>
								<view class="list_box_right" style="width: 70%;">
									<view style="line-height: 1.5;">
										{{item.title}}
									</view>
									<view
										style="color:#3485e9;margin-top: 10upx; display: flex;justify-content: space-between;align-items: center;">
										{{item.start}} - {{item.end}}
										<view>
											<u-tag :text="getActionType(item.actionType)" mode="light"></u-tag>
										</view>
									</view>
								</view>
							</template>
						</view>
						<template slot="right">
							<view class="slot-button" v-if="currentMode==0&&!item.closed">
								<view class="slot-button-con" style="background-color:#ff5a5f"
									@click="swipeClick({ content: { text: '删除' } }, index, item)">
									<text class="slot-button-text">删除</text>
								</view>
								<view class="slot-button-con" style="background-color:#3485e9"
									@click="swipeClick({ content: { text: '编辑' } }, index, item)">
									<text class="slot-button-text">编辑</text>
								</view>
							</view>
						</template>
					</uni-swipe-action-item>
				</uni-swipe-action>
			</view>
		</view>
	</view>
</template>

<script>
	import LuncCalendar from '../component/lunc-calendar/lunc-calendar'
	import UserGroup from './modules/userGroup.vue'
	import SelectUser from '@/components/selectUser/index.vue'
	import {
		postFormAction,
	} from "@/utils/request.js";
	import moment from 'moment'
	import {
		debounce
	} from '@/utils/util.js'
	import {
		getTimeBetween,
		filterData,
		actionTypeList
	} from './schedule.js'
	export default {
		components: {
			LuncCalendar,
			UserGroup,
			SelectUser
		},
		data() {
			this.fetch = debounce(this.fetch, 800, false)
			this.fetchAll = debounce(this.fetchAll, 800, false)
			return {
				url: {
					del: '/plan/del',
					listPhase: '/plan/listPhase', //我的日程
					listPhaseByUsers: '/plan/listPhaseByUsers', // 获取多用户日程
					getDeptUsers: '/user/getDeptUsers', //获取部门人员
					listFavorite: '/user/listFavorite', //关注人员list
					createFavorite: '/user/createFavorite', //关注人员新增
					delFavorite: '/user/delFavorite', //关注人员删除
					listLeaders: '/user/listLeaders', //领导日程list
				},
				list: [],
				sheetShow: false,
				sheetList: [{
					text: '我的日程',
				}, {
					text: '部门人员'
				}, {
					text: '我关注的'
				}, {
					text: '领导日程'
				}],
				currentMode: 0,
				queryParams: {
					beginDate: '',
					endDate: ''
				},
				users: '',
				shrinkType: 'month',
				currentType: 'day', // day week month
				deptUsers: [], //部门人员
				leaders: [], //领导list
				plainOptions: [], //我关注的人员
				isRefresh: false,
				allList: [], //当前月或者周的全部数据
				actionType: '0'
			}
		},
		onLoad() {
			this.updateTitle('我的日程')
			this.queryParams.beginDate = moment().format("YYYY-MM-DD")
			this.queryParams.endDate = moment().format("YYYY-MM-DD")
			this.fetch()

			this.getDeptUsersData()
			this.getListFavoriteData()
			this.getListLeadersData()
		},
		onShow() {
			var pages = getCurrentPages();
			var currPage = pages[pages.length - 1]; //当前页面
			if (currPage.isRefresh) {
				this.init()
				currPage.isRefresh = false
			}
		},
		mounted() {
			this.fetchAll()
		},
		methods: {
			moment,
			getActionType(val) {
				const record = actionTypeList.find(item => item.value == val)
				if (record) {
					return record.label
				}
				return ''
			},
			init() {
				this.fetch()
				this.fetchAll()
			},
			//类型
			handleActionType(val) {
				this.actionType = val
				this.init()
			},
			handleSheetClick(val) {
				this.currentMode = val
				if (this.currentMode == 1) {
					this.users = this.deptUsers.map(item => item.value).join(',')
				} else if (this.currentMode == 2) {
					this.users = this.plainOptions.map(item => item.value).join(',')
				} else if (this.currentMode == 3) {
					this.users = this.leaders.map(item => item.value).join(',')
				} else {
					this.users = ''
				}
				this.updateTitle(this.sheetList[this.currentMode].text)
				this.init()

			},
			handleDayChange(e) {
				// if (this.shrinkType == 'week') {
				// 	if (this.queryParams.beginDate == e.date) return
				// 	this.handleSetData()
				// } else if (this.shrinkType == 'month') {
				// 	this.handleSetData()
				// } else {
				// 	this.queryParams.beginDate = e.date
				// 	this.queryParams.endDate = e.date
				// }
				this.queryParams.beginDate = e.date
				this.queryParams.endDate = e.date
				this.fetch()
			},
			//获取当前是周还是月
			handleShrinkClick(type) {
				this.shrinkType = type
				this.currentType = type
			},
			//处理周和月逻辑
			handleSetData() {
				const params = {
					beginDate: '',
					endDate: '',
				}
				if (this.shrinkType == 'week') {
					const allWeekList = this.$refs.luncCalendarRef.allWeekList
					const tranCurrent = this.$refs.luncCalendarRef.tranCurrent
					const currentWeekData = allWeekList[tranCurrent][0]
					params.beginDate = currentWeekData[0].date
					params.endDate = currentWeekData[currentWeekData.length - 1].date
				} else if (this.shrinkType == 'month') {
					const allMonthList = this.$refs.luncCalendarRef.allMonthList
					const tranIndex = this.$refs.luncCalendarRef.tranIndex
					const currentMonthData = allMonthList[tranIndex]
					params.beginDate = currentMonthData[0][0].date
					params.endDate = currentMonthData[currentMonthData.length - 1][currentMonthData[
						currentMonthData.length - 1].length - 1].date
				}
				return params
			},

			//获取我的日程
			async fetch() {
				this.list = await this.getData({
					beginDate: this.queryParams.beginDate,
					endDate: this.queryParams.endDate,
				}, 'day_list')

			},
			//月change
			handleMonthChange() {
				this.fetchAll()
			},
			//获取当前周或者月的全部日程
			async fetchAll() {
				const params = await this.handleSetData()
				this.allList = await this.getData({
					...params,
				}, 'range_list')
				let dateList = []
				this.allList.forEach(item => {
					const dates = getTimeBetween(item.myDate, item.endDate)
					dates.forEach(el => {
						dateList.push({
							date: el,
							title: ''
						})
					})
				})
				dateList = filterData(dateList)
				//单天查询应该查出区间内的数据
				this.addSign(dateList)
			},

			async getData(params = {}, type = 'day_list') {
				try {
					uni.showLoading({
						title: '加载中',
						mask: true
					})
					let _list = []
					if (this.currentMode == 0) {
						const res = await postFormAction(this.url.listPhase, {
							...params,
							actionType: this.actionType,
						});
						const {
							data
						} = res
						if (data.list) {

							if (data.list && data.list.length > 0) {
								const list = data.list;
								list.forEach((m) => {
									for (let v in m) {
										const temp = m[v];
										if (temp && temp.length) {
											temp.forEach((item) => {
												if (type == 'day_list' || this.currentType == 'day' ||
													this.currentType == 'month') {
													_list.push({
														...item,
														title: `${item.title}`,
														start: moment(item.myDate).format(
															'HH:mm'),
														end: moment(item.endDate).format(
															'HH:mm'),
													});
												} else {
													for (let n in item) {
														const td = item[n];
														if (td && td.length) {
															td.forEach((t) => {
																_list.push({
																	...t,
																	title: `${t.title}`,
																	start: moment(t
																			.myDate)
																		.format(
																			'HH:mm'),
																	end: moment(t
																			.endDate)
																		.format(
																			'HH:mm'),
																});
															});
														}
													}
												}
											});
										}
									}
								});
							}
						}
					} else {
						if (this.users) {
							const res = await postFormAction(this.url.listPhaseByUsers, {
								...params,
								users: this.users,
								actionType: this.actionType,
								// beginDate: this.queryParams.beginDate,
								// endDate: this.queryParams.endDate,
								// actionType: isArray(c_type.value) && c_type.value.length ? c_type.value.join(',') : '',
							});
							const {
								data
							} = res
							if (data && data.length) {
								data.forEach((it) => {
									if (it.list && it.list.length) {
										it.list.forEach((m) => {
											for (let v in m) {
												const temp = m[v];
												if (temp && temp.length) {
													temp.forEach((item) => {
														if (type == 'day_list' || this
															.currentType == 'day' || this
															.currentType == 'month') {
															_list.push({
																...item,
																title: `${item.title}`,
																day: moment(item
																		.myDate)
																	.format(
																		'YYYY-MM-DD'
																	),
																start: moment(item
																		.myDate)
																	.format(
																		'HH:mm'
																	),
																end: moment(item
																		.endDate)
																	.format(
																		'HH:mm'
																	),
																realName: it.realName
															});
														} else {
															for (let n in item) {
																const td = item[n];
																if (td && td.length) {
																	td.forEach((t) => {
																		_list
																			.push({
																				...
																				t,
																				title: `${t.title}`,
																				day: moment(
																						item
																						.myDate
																					)
																					.format(
																						'YYYY-MM-DD'
																					),
																				start: moment(
																						t
																						.myDate
																					)
																					.format(
																						'HH:mm'
																					),
																				end: moment(
																						t
																						.endDate
																					)
																					.format(
																						'HH:mm'
																					),
																				resourceId: t
																					.userName,
																				realName: it
																					.realName
																			});
																	});
																}
															}
														}
													});
												}
											}
										});
									}
								});
							}
						}
					}
					return _list
				} catch (e) {
					console.error("fetch", e)
				} finally {
					uni.hideLoading()
				}
			},
			// 添加标记
			addSign(addList) {
				this.$refs.luncCalendarRef.clearSignList();
				// let addList = [{date: "2023-06-28",title: ""}];
				// 调用 addSignList 方法，传入需要添加的标记数组
				this.$refs.luncCalendarRef.addSignList(addList);
			},
			// 删除标记
			deleteSign() {
				let deleteList = [{
					date: "2023-06-01",
					title: ""
				}];
				// 调用 deleteSignList 方法，传入需要删除的标记数组
				this.$refs.luncCalendarRef.deleteSignList(deleteList);
			},

			//删除
			swipeClick(e, index, item) {
				let {
					content
				} = e;
				if (content.text === "删除") {
					uni.showModal({
						title: "提示",
						content: "是否确定删除",
						success: (res) => {
							if (res.confirm) {
								this.handleDelete(item, index);
							} else if (res.cancel) {
								console.log("用户点击取消");
							}
						},
					});
				} else if (content.text === "编辑") {
					this.goPath({
						record: item,
						isUpdate: 1
					})
				}
			},
			//单个删除
			handleDelete(record, index) {
				uni.showLoading({
					title: '删除中',
					mask: true
				})
				postFormAction(this.url.del, {
					id: record.id,
				}).then((res) => {
					uni.showToast({
						title: res.msg,
						icon: 'none'
					});
					if (res.code == 200) {
						this.list.splice(index, 1);
					}

				}).finally(() => {
					uni.hideLoading()
				});
			},

			//删除关注人员
			handleDelFavorite(ids) {
				uni.showLoading({
					title: '删除中',
					mask: true
				})
				postFormAction(this.url.delFavorite, {
					ids
				}).then((res) => {
					uni.showToast({
						title: res.msg,
						icon: 'none'
					});
					if (res.code == 200) {
						this.getListFavoriteData()
					}

				}).finally(() => {
					uni.hideLoading()
				});
			},
			//新增
			handlePlus() {
				this.goPath({
					isUpdate: 0
				})
			},
			//我关注的 新增人员
			handleAddUser() {
				this.$refs.selectUserRef.open()
			},
			//选择用户回调
			handleSelectUserConfirm({
				selectUserList,
				label,
				value
			}) {
				this.save(value)
			},
			async save(data) {
				if (!data) {
					uni.showToast({
						title: '新增数据不能为空',
						icon: 'none',
					});
					return
				}
				try {
					let keys = ''
					const datas = data.split(',')
					const hadDatas = this.plainOptions.map(item => item.item)
					if (hadDatas && hadDatas.length > 0) {
						keys = datas.filter(val => !hadDatas.includes(val)).join(',')
					}
					if (!keys) {
						uni.showToast({
							title: '新增重复',
							icon: 'none',
						});
						return
					}
					uni.showLoading({
						title: '新增中',
						mask: true
					})
					const res = await postFormAction(this.url.createFavorite, {
						items: keys
					});
					this.getListFavoriteData();
					uni.showToast({
						title: '新增成功',
						icon: 'none',
					});
				} catch (error) {
					console.error(error);
				} finally {
					uni.hideLoading()
				}
			},
			//获取部门用户
			async getDeptUsersData() {
				try {
					const res = await postFormAction(this.url.getDeptUsers);
					const {
						data
					} = res
					this.deptUsers = data.list || [];
					this.deptUsers.forEach((item) => {
						item.label = item.realName;
						item.value = item.name;
					});
				} catch (error) {
					console.error(error);
				} finally {}
			},
			//获取关注人员
			async getListFavoriteData() {
				try {
					const res = await postFormAction(this.url.listFavorite);
					const {
						data
					} = res
					this.plainOptions = data || [];
					this.plainOptions.forEach((item) => {
						item.label = item.realName;
						item.value = item.item;
					});
				} catch (error) {
					console.error(error);
				} finally {}
			},
			//获取领导
			async getListLeadersData() {
				try {
					const res = await postFormAction(this.url.listLeaders);
					const {
						data
					} = res
					this.leaders = data || [];
					this.leaders.forEach((item) => {
						item.label = item.realName;
						item.value = item.name;
					});
				} catch (error) {
					console.error(error);
				} finally {}
			},
			//选择查询的用户回调
			handleUserSuccess(val) {
				this.users = val
				this.init()
			},

			//单击查看详情
			handleItem(item) {
				this.goPath({
					record: item,
					isUpdate: 2
				})
			},
			//跳转
			goPath({
				record = {},
				isUpdate = 0
			}) {
				uni.navigateTo({
					url: `/cmn/schedule/ScheduleAddOrEdit?record=${JSON.stringify(record)}&isUpdate=${isUpdate}`,
				});
			},
			updateTitle(title) {
				// 微信支持
				// // 获取当前页面对象
				// const pages = getCurrentPages(); // 返回当前页面栈的信息
				// const currentPage = pages[pages.length - 1]; // 获取最后一个打开的页面

				// // 设置新的标题
				// currentPage.$page.meta.title = title;

				// 更新导航栏标题
				uni.setNavigationBarTitle({
					title,
				});
			},
		},
	}
</script>
<style>
	page {
		height: 100%;
		background-color: #f9f9f9;
	}
</style>
<style lang="less" scoped>
	.schedule_style {
		height: 100%;
		display: flex;
		flex-direction: column;

		.schedule_list {
			flex: 1;
			overflow-y: auto;
			margin-top: 20upx;

			.list_box {
				display: flex;
				justify-content: space-between;
				border-radius: 6upx;
				padding-bottom: 40upx;

				&_left {
					width: 20%;
				}

				&_right {
					width: 80%;
					overflow: hidden;
					background-color: #fff;
					padding: 10upx;
					box-shadow: 10px 10px #ffffff, -10px 10px #ffffff, 10px -10px #ffffff, -10px -10px #ffffff;
				}
			}
		}
	}

	.slot-button {
		/* #ifndef APP-NVUE */
		display: flex;
		height: 100%;
		/* #endif */
		flex: 1;
		flex-direction: row;
		justify-content: center;
		align-items: center;
		background-color: transparent;
		padding-bottom: 20upx;

		.slot-button-con {
			height: 100%;
			width: 100%;
			padding: 0 20upx;
			//   border-radius: 16upx;
			/* #ifndef APP-NVUE */
			display: flex;
			height: 100%;
			/* #endif */
			display: flex;
			// flex: 1;
			flex-direction: row;
			justify-content: center;
			align-items: center;
			margin-right: 10rpx;
			margin-left: 10rpx;
		}

		.slot-button-text {
			color: #ffffff;
			font-size: 14px;
		}
	}
</style>